package com.ljf.spring;

import com.ljf.framework.exception.LjfExceptionHandler;
import com.ljf.framework.log.LjfLogManager;
import com.ljf.framework.log.LjfLogService;
import com.ljf.framework.result.JsonResult;
import com.ljf.framework.result.JsonResultEnum;
import com.ljf.framework.result.JsonResultUtil;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 说明：可以拦截servlet所有的异常，包括filter和controller层
 *
 * @Auther: lijinfeng
 * @Date: 2024/4/25
 */
public class LjfErrorController extends BasicErrorController {
    LjfLogService log = LjfLogManager.getLogger(LjfErrorController.class);


    public LjfErrorController() {
            super(new DefaultErrorAttributes(), new ErrorProperties());
    }


    /**
     * produces 设置返回的数据类型：application/json
     *
     * @param request 请求
     * @return 自定义的返回实体类
     */
    @Override
    @RequestMapping(value = "", produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {

        Map<String, Object> body = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));

        body.forEach((k,v) -> {
            System.out.println("body:"+k+":"+v);
        });
        HttpStatus httpStatus = HttpStatus.OK;
        // 如果是内部异常
        if ("Internal Server Error".equals(body.get("error"))){
            // 获取手动throw异常，状态码为200
            String errMsg = LjfExceptionHandler.getExceptionForServlet();
            JsonResultEnum anEnum = JsonResultUtil.getEnum(errMsg, JsonResultEnum.class);
            if (!anEnum.equals(JsonResultEnum.NULL)) {
                log.error("发生了错误：" + anEnum.toString());
                return new ResponseEntity(JsonResult.error(anEnum,errMsg,null), httpStatus);
            }
            return new ResponseEntity(JsonResult.error(errMsg), httpStatus);
        }

        // 服务端未知异常
        httpStatus = HttpStatus.valueOf(Integer.parseInt(body.get("status").toString()));
        log.error("发生了错误：" + httpStatus.value()+":"+httpStatus.getReasonPhrase());
        return new ResponseEntity(JsonResult.error(body), httpStatus);
    }

}
